package com.tlgen.orm.support.chain;

import com.tlgen.orm.components.rest.model.RequestMethodAndUrl;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

// 新增执行管线类
public class ExecutionPipeline {

    private final List<ExecutionStage> stages = new ArrayList<>();

    public ExecutionPipeline addStage(ExecutionStage stage) {
        stages.add(stage);
        return this;
    }

    public Object execute(HttpServletRequest request,
                          RequestMethodAndUrl requestMethodAndUrl,
                          Map<String, Object> params) throws Exception {
        Object result = null;

        for (ExecutionStage stage : stages) {
            if (stage.shouldExecute(requestMethodAndUrl)) {
                result = stage.execute(request, requestMethodAndUrl, params, result);

                // 如果阶段表明应该终止流程
                if (stage.shouldTerminate()) {
                    break;
                }
            }
        }

        return result;
    }
}

